<?php
namespace OpenApi\Controller;
use Think\Controller;
//外部接口
class CronController extends Controller {
	
    public function _initialize(){
		//数据库连接基础配置-begin
		C('db_config.DB_TYPE',C('DB_TYPE'));
		C('db_config.DB_HOST',C('DB_HOST'));
		C('db_config.DB_USER',C('DB_USER'));
		C('db_config.DB_PWD',C('DB_PWD'));
		C('db_config.DB_PORT',C('DB_PORT'));
		C('db_config.DB_CHARSET',C('DB_CHARSET'));
		//数据库连接基础配置-end
    }
	
	//接收订单
	public function cron_wcf(){
		$map=array();
		// $map['user_code']	='PN1MBDNQ3G';
		// $map['user_key']	='PN1MBDNQ3G';
		// $merchant_code		='PN1MBDNQ3G';
		$map['user_code']	='DF1X9GN675';
		$map['user_key']	='DF1X9GN675';
		$merchant_code		='DF1X9GN675';

		$u=M('User');
		$u_info=$u->where($map)->find();
		$username=$u_info['username'];
		$db_name=C('DB_PREFIX_T').$username;
		C('db_config.DB_NAME',$db_name);
		$m=M('Pushorder',C('DB_PREFIX_T'), C('db_config'));//订单
		$g=M('Pushordergoods',C('DB_PREFIX_T'), C('db_config'));//订单下产品
		$p=M('Printorder',C('DB_PREFIX_T'), C('db_config'));
		$pro=M('Product',C('DB_PREFIX_T'), C('db_config'));//产品列表
		//获取数据
		$order_id = '';

		//已经出库  已经放行的推过去
		$m_info=$m->where(array('cron_wcf'=>2,'logistics_no'=>['neq',""],'is_delivery'=>1,'is_pass'=>1))->order('id desc')->limit(20)->select();
		if(empty($m_info)){//没有数据就关闭程序
			$message = '数据为空，程序已中止';
			file_put_contents('./log/PN_WCF_CALLBACK.log',date('Y-m-d H:i:s').var_export($message,true).PHP_EOL,FILE_APPEND);//日志导出sql
			die;
		}

		//WCF服务  数据拼接
		$url = "http://47.101.179.220:3306/DisAndRd32.svc?wsdl";//webservice地址(WCF地址)
		foreach ($m_info as $k => $val) {
			$data[0]['SOCode'] = $val['old_order_no'];
			$data[0]['TrackNo'] = $val['logistics_no'];
			$order_id = $val['id'];
			$order_goods_info = $g->where(array('order_id'=>$val['id']))->select();
			foreach ($order_goods_info as $key => $value) {
				$data[0]['list'][$key]=[
					'cBatch'=>'',
					'cInvCode'=>$value['bar_code'],
				];
			}
			file_put_contents('./log/PN_WCF_DATA.log',date('Y-m-d H:i:s').var_export(json_encode($data),true).PHP_EOL,FILE_APPEND);//日志导出sql
			$data_back = $this->WCF_metch($url,json_encode($data));
			if($data_back['is_success'] == 1){
				if($m->where(array('id'=>$order_id))->save(array('cron_wcf'=>1))){
					$message = $val['old_order_no'].'推送成功';
				}else{
					$message = $val['old_order_no'].'数据库更新失败';
				}
				file_put_contents('./log/PN_WCF_CALLBACK.log',date('Y-m-d H:i:s').var_export($message,true).PHP_EOL,FILE_APPEND);//日志导出sql
			}else{
				$info = '1.'.$data_back['message'];
				if(mb_strpos($info,'在U8中不存在') || mb_strpos($info,'该销售订单已回传生成销售发货单和出库单')){
					if($m->where(array('id'=>$order_id))->save(array('cron_wcf'=>1))){
						$message = $val['old_order_no'].'数据库更新成功';
					}else{
						$message = $val['old_order_no'].'数据库更新失败';
					}
					file_put_contents('./log/PN_WCF_CALLBACK.log',date('Y-m-d H:i:s').var_export($message,true).PHP_EOL,FILE_APPEND);//日志导出sql
				}else{
					file_put_contents('./log/PN_WCF_CALLBACK.log',date('Y-m-d H:i:s').var_export("WCF服务返回:".$data_back['message'],true).PHP_EOL,FILE_APPEND);//日志导出sql
				}
			}
		}
	}
	
	//调用WCF服务
	public function WCF_metch($url,$param){
		file_put_contents('./log/PN_WCF_DATA.log',date('Y-m-d H:i:s').var_export($param,true).PHP_EOL,FILE_APPEND);
		header('Content-Type: text/plain');
		$wcfClient = new \SoapClient($url);
		$arr=[
			'JsonData'=>$param
		];

		$result1 = $wcfClient->InsertOrder($arr);
		$info = $result1->InsertOrderResult;

		$data = [];
		if($info->IsSuccess){
			$data['is_success'] = 1;
		}else{
			$data['is_success'] = 0;
		}
		$data['message']=$info->MESSAGE;
		return $data;
	}

	public function cron_mttlm(){
		$map=array();
		$map['user_code']	='DF1X9GN675';
		$map['user_key']	='DF1X9GN675';
		$merchant_code		='DF1X9GN675';

		$u=M('User');
		$u_info=$u->where($map)->find();
		$username=$u_info['username'];
		$db_name=C('DB_PREFIX_T').$username;
		C('db_config.DB_NAME',$db_name);
		$m=M('Pushorder',C('DB_PREFIX_T'), C('db_config'));//订单
		$g=M('Pushordergoods',C('DB_PREFIX_T'), C('db_config'));//订单下产品
		$p=M('Printorder',C('DB_PREFIX_T'), C('db_config'));
		$pro=M('Product',C('DB_PREFIX_T'), C('db_config'));//产品列表
		//获取数据
		$order_id = '';
		$m_info=$m->where(array('cron_wcf'=>0,'status'=>['neq','-1'],'is_delivery'=>0,'is_pass'=>['EXP','IS NULL']))
		->order('id desc')->limit(50)->select();
		if(empty($m_info)){//没有数据就关闭程序
			$message = '数据为空，程序已中止';
			file_put_contents('./log/PN_MTTLM_CALLBACK.log',date('Y-m-d H:i:s').var_export($message,true).PHP_EOL,FILE_APPEND);//日志导出sql
			exit;
		}

		$order_info = [];
		foreach ($m_info as $k => $val) {
            $push_status = $val['push_status'];
			$order_info['order_sn'] = $val['old_order_no'];
			$order_info['buyer_name'] = $val['buyer_name'];
			$order_info['buyer_phone'] = $val['user_phone'];
			$order_info['buyer_idcard'] = $val['buyer_idcard'];
			$order_info['consignee'] = $val['user_name'];
			$order_info['tel'] = $val['user_phone'];
			$order_info['province'] = $val['province'];
			$order_info['city'] = $val['city'];
			$order_info['district'] = $val['area'];
			$order_info['address'] = $val['user_address'];
			$order_info['pay_no'] = '';
			$order_info['discount'] = '';
			$order_info['come_from'] = 'ERP';
			$order_info['pay_id'] = '';
			$order_info['shipping_fee'] = $val['ems_fee'];
			$order_info['insure_fee'] = $val['insure_amount'];
			$order_info['cod'] = $val['cod'];
			$order_info['cod_money'] = $val['cod_money'];
            $order_info['trade_model'] = $val['trade_model'];
            $order_info['warehouse_code'] = $val['warehouse_code'];
			// $order_info[$k]['remark'] = $val['old_order_no'];
			$order_info['taxes'] = $val['goods_tax'];
			// $order_info[$k]['insure_fee'] = $val['old_order_no'];

			//订单下的产品数据
			$goods_info = $g->where(['order_id'=>$val['id']])->select();
			$goods_list = [];
			foreach ($goods_info as $key => $value) {
				$goods_list[$key]['bar_code'] = $value['bar_code'];
				$goods_list[$key]['goods_nums'] = $value['goods_nums'];
				$goods_list[$key]['goods_price'] = $value['goods_price'];
				$goods_list[$key]['goods_amount'] = $value['goods_nums']*$value['goods_price'];
			}
			$order_info['goodslist'] = $goods_list;

			$push_data = [
			'user_code'=>$map['user_code'],
			'user_key'=>$map['user_key'],
			'data'=>$order_info
			];
			file_put_contents('./log/PN_MTTLM_DATA.log',date('Y-m-d H:i:s').var_export($push_data,true).PHP_EOL,FILE_APPEND);//日志导出sql
			
			$url="http://www.mttlm.com/api/erp/api.php?act=erpPush";
//            $url="http://local.mttlm.com/api/erp/api.php?act=erpPush";
			$api_res_un=json_decode(push($url,$push_data),true);

			switch ($api_res_un['code']) {
				case 0:
					file_put_contents('./log/PN_MTTLM_CALLBACK.log',date('Y-m-d H:i:s').var_export($api_res_un['data'],true).PHP_EOL,FILE_APPEND);//日志导出sql
                    $m->where(array('old_order_no'=>$val['old_order_no']))->save(array('cron_wcf'=>2,'fail_reason'=>'','abnormal_price'=>0));
                    break;
				case 1:
					$m->where(array('old_order_no'=>$val['old_order_no']))->save(array('cron_wcf'=>2,'fail_reason'=>'','abnormal_price'=>0));
					file_put_contents('./log/PN_MTTLM_CALLBACK.log',date('Y-m-d H:i:s').var_export('添加成功',true).PHP_EOL,FILE_APPEND);//日志导出sql
//                    if(!$push_status){//是否推送
//                        $this->pushoms_auto($map,$val['old_order_no']);//自动推送
//                    }
					break;
				case 2:
					$m->where(array('old_order_no'=>$val['old_order_no']))->save(['abnormal_price'=>1,'fail_reason'=>$api_res_un['data']]);
					file_put_contents('./log/PN_MTTLM_CALLBACK.log',date('Y-m-d H:i:s').var_export($api_res_un['data'],true).PHP_EOL,FILE_APPEND);//日志导出sql
					break;
			}
			//返回值操作
			// 
		}
        exit;
	}

//自动推送ERP（添加到定时任务）
	public function pushoms_auto(){
        $map=array();
        $map['user_code']	='DF1X9GN675';
        $map['user_key']	='DF1X9GN675';
        $merchant_code		='DF1X9GN675';

		$u=M('User');
		$p=M('PushorderCron');
		$pc=M('PushorderCronDetail');

		$u_info=$u->where($map)->find();
		$username=$u_info['username'];
		$db_name=C('DB_PREFIX_T').$username;
		C('db_config.DB_NAME',$db_name);
		$m=M('Pushorder',C('DB_PREFIX_T'),C('db_config'));

        $m_list=$m->field('id')->where(array('cron_wcf'=>2,'status'=>1,'push_status'=>0,'is_pass'=>['EXP','IS NULL']))->select();

        if(empty($m_list)){
            alert_json(0,'没有要推送的新订单');
            die;
        }
        $data_p['warehouse_code']='11330213';
        $data_p['username']=$username;
        $data_p['add_time']=time();

        $p_res=$p->add($data_p);
        if(!$p_res){
            alert_json(0,'添加计划任务失败');
        }else{
            $data=array();
            $ids=array();
            $time=time();
            foreach($m_list as $k=>$v){
                $data[$k]['order_id']=$v['id'];
                $data[$k]['add_time']=$time;
                $data[$k]['porder_id']=$p_res;
                $ids[]=$v['id'];
            }
            $res=$pc->addAll($data);
            if(!$res){
                alert_json(0,'失败');
            }else{
                $res_m=$m->where(array('id'=>array('in',$ids)))->save(array('push_status'=>2));
                return true;
            }
        }

	}
}